import { Badge, Button, message, Modal, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { ModalForm, ProFormDateTimeRangePicker, ProFormInstance, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import $utils from '@/utils/utils';

// 驿站接口导入
import { getStationName } from '@/services/postHouse';
// 快递公司接口导入
import { getExpressData, } from '@/services/company';
import { getPushList, repushByDb, rePushByIds, setSolve } from '@/services/expressRoute';
import moment from 'moment';

const initDate = {
    startTime: moment().subtract(2, 'days').startOf('day'),     //  开始时间
    endTime: moment().endOf('day'),     //  结束时间
    status: 2,
    solve: 1,
};

const errorTypeData = [
    { label: '全部', value: 0 },
    { label: '入库对接失败', value: 1 },
    { label: '入库未对接', value: 2 },
    { label: '出库对接失败', value: 3 },
    { label: '出库未对接', value: 4 },
    { label: '退回对接失败', value: 5 },
    { label: '退回未对接', value: 6 },
]

const ExpressRouteList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [initParams, setParams] = useState<any>();
    const [current, setCurrent] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(20);

    const [visible, setVisible] = useState<boolean>(false);

    const [expressList, setExpressList] = useState<API.Select[]>([]);
    const [stationNames, setStationNames] = useState<API.Select[]>([]);

    const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);    // TODO 已选择数据ids
    const [selectedRouteData, setSelectedRouteData] = useState<any>([]);    // TODO 已选择数据{id, pushTime}


    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = l_state ? {
                ...l_state,
                dateTime: [moment(l_state?.startTime) || initDate.startTime, moment(l_state?.endTime) || initDate.endTime],
            } : {
                ...initDate,
                dateTime: [initDate.startTime, initDate.endTime],
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        const data = {
            ...initDate,
            dateTime: [initDate.startTime, initDate.endTime],
        }
        if (JSON.stringify(initParams) === JSON.stringify(data)) {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    useEffect(() => {
        const getOptions = async () => {
            let result = $utils.getStorage('express_options');
            !result && (result = await getExpressData());
            setExpressList(result);
        };
        getOptions();
        const getStationNames = async () => {
            try {
                const msg = await getStationName({ name: '' });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.map((item: { id: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                        });
                    });
                    setStationNames(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
                message.error('驿站名称列表获取失败!');
            }
        };

        getStationNames()
    }, []);

    const columns: ProColumns<any>[] = [
        {
            title: '时间',
            dataIndex: 'dateTime',
            hideInTable: true,
            valueType: 'dateTimeRange',
            search: {
                transform: (value: any) => ({ startTime: value[0], endTime: value[1] }),
            },
            width: '120px',
            order: 5,
        },
        {
            title: '快递公司',
            dataIndex: 'expressId',
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                placeholder: '全部',
                options: expressList
            },
            width: 150,
            order: 5,
        },
        {
            title: '运单号',
            dataIndex: 'expCode',
            width: 200,
            order: 5,
        },
        {
            title: '驿站名称',
            dataIndex: 'stationId',
            valueType: 'select',
            order: 5,
            width: 200,
            fieldProps: {
                showSearch: true,
                options: stationNames
            }
        },
        {
            title: '对接状态',
            dataIndex: 'status',
            valueType: 'select',
            order: 4,
            width: 120,
            fieldProps: {
                allowClear: false,
                options: [
                    { label: '全部', value: 0 },
                    { label: '成功', value: 1 },
                    { label: '失败', value: 2 },
                ]
            }
        },
        {
            title: '失败类型',
            dataIndex: 'errorType',
            valueType: 'select',
            width: 150,
            fieldProps: {
                placeholder: '全部',
                allowClear: false,
                options: errorTypeData,
            },
            render: (dom: any, record: any) => {
                return (<div>{record.errorType === 0 ? '--' : dom}</div>)
            }
        },
        {
            title: '失败原因',
            dataIndex: 'error',
            search: false,
            width: 520,
            render: (dom: any, record: any) => {
                return (<div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>{dom}</div>)
            }
        },
        {
            title: '推送时间',
            dataIndex: 'pushTime',
            search: false,
            width: 120,
        },
        {
            title: '处理状态',
            dataIndex: 'solve',
            valueType: 'select',
            width: 120,
            fieldProps: {
                placeholder: '全部',
                allowClear: false,
                options: [
                    { label: '全部', value: 0 },
                    { label: '未处理', value: 1 },
                    { label: '已处理', value: 2 },
                ],
            }
        },
    ];

    // 根据已选项获取数据  TODO: 暂废弃
    const getDataBySelect = async () => {
        let result: any = [], ids = Object.values(selectedRowKeys).flat();
        if (ids.length === 0) {
            message.warn('请至少选择一个订单')
            return []
        }
        const pages = Object.keys(selectedRowKeys);
        const { current, pageSize, ...others } = initParams;
        const msg = await getPushList({ current: 1, pageSize: +pages.sort().reverse()[0] * 20, ...others });
        if (msg.code === 0) {
            const list = msg.body.list;
            ids.map(id => {
                const item = list.find((i: any) => i.id === id);
                result.push({ id, pushTime: item.pushTime, });
            })
        }
        return result;
    }

    // 重新补推数据确认
    const againRePushByIds = async () => {

        if (selectedRouteData.length < 1) { return; }
        Modal.confirm({
            className: 'again-send',
            icon: false,
            width: '320px',
            title: (<div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>重新补推数据</div>),
            content: (<div>
                <div style={{ textAlign: 'center', color: 'rgba(136, 136, 136, 100)', fontSize: 15, marginBottom: 12, }}>确定重新补推数据？</div>
            </div>),
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 重新补推接口
                const msg = await rePushByIds({ data: JSON.stringify(selectedRouteData) });
                if (msg.code === 0) {
                    message.success('操作成功');
                    actionRef && (actionRef?.current?.reload());
                    setSelectedRowKeys([]);
                    setSelectedRouteData([])
                }
            }
        });
    }

    // 批量处理确认
    const batchSetSolve = async () => {

        if (selectedRouteData.length < 1) { return; }
        Modal.confirm({
            className: 'again-send',
            icon: false,
            width: '320px',
            title: (<div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>批量处理</div>),
            content: (<div>
                <div style={{ textAlign: 'center', color: 'rgba(136, 136, 136, 100)', fontSize: 15, marginBottom: 12, }}>确定批量标记已处理？</div>
            </div>),
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 批量处理接口
                const msg = await setSolve({ data: JSON.stringify(selectedRouteData) });
                if (msg.code === 0) {
                    message.success('操作成功');
                    actionRef && (actionRef?.current?.reload());
                    setSelectedRowKeys([]);
                    setSelectedRouteData([])
                }
            }
        });
    }

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                tableAlertRender={false}
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: false,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setCurrent(current);
                        setPageSize(pageSize);
                    }
                }}
                formRef={formRef}
                form={{
                    initialValues: initParams
                }}
                search={true ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: 6,
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                const data = {
                                    ...initDate,
                                    dateTime: [initDate.startTime, initDate.endTime],
                                };
                                setParams(data);
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                title={() => [
                    <Space key="index">
                        <Access key="index1" accessible={true}>
                            <Button type="primary" onClick={() => {
                                againRePushByIds();
                            }}>重新补推数据</Button>
                        </Access>
                        <Access key="index2" accessible={true}>
                            <Button type="primary" onClick={() => {
                                batchSetSolve()
                            }}>批量处理</Button>
                        </Access>
                        <Access key="index3" accessible={true}>
                            <Button type="primary" onClick={() => {
                                setVisible(true);
                            }}>手动补推</Button>
                        </Access>
                    </Space>
                ]}
                options={false}
                request={async (params: any) => {
                    if (!params.startTime) { params.startTime = initDate.startTime.format('YYYY-MM-DD HH:mm:ss'); }
                    if (!params.endTime) { params.endTime = initDate.endTime.format('YYYY-MM-DD HH:mm:ss'); }
                    if (!params.status && typeof params.status !== 'number') { params.status = initDate.status; }
                    if (!params.solve && typeof params.solve !== 'number') { params.solve = initDate.solve; }
                    const msg = await getPushList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '快递路由对接',
                            path: '/OperationsMange/ExpressRoute',
                            isTopMenu: true,
                            state: params
                        });
                        setParams(params);
                    }
                    return {
                        data: msg.body?.list || [],
                        success: msg.code === 0,
                        total: msg.body?.count || 0,
                    }
                }}
                rowSelection={{
                    // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                    // 注释该行则默认不显示下拉选项
                    selectedRowKeys: selectedRowKeys,
                    onSelect: (record: any, selected, selectedRows) => {

                        const new_selectedRouteData = [...selectedRouteData], new_selectedRowKeys = [...selectedRowKeys];
                        if (selected) {
                            new_selectedRouteData.push({ id: record.id, pushTime: record.pushTime });
                            new_selectedRowKeys.push(record.id);
                        } else {
                            const routeIndex = new_selectedRouteData.findIndex(item => item.id === record.id), keyIndex = new_selectedRowKeys.indexOf(record.id);
                            routeIndex > -1 && new_selectedRouteData.splice(routeIndex, 1)
                            keyIndex > -1 && new_selectedRowKeys.splice(keyIndex, 1);
                        }
                        setSelectedRouteData(new_selectedRouteData)
                        setSelectedRowKeys(new_selectedRowKeys)
                    },
                    onSelectAll: (selected, selectedRows, changeRows: any) => {
                        const new_selectedRouteData = [...selectedRouteData], new_selectedRowKeys = [...selectedRowKeys];
                        if (selected) {
                            for (let i = 0; i < changeRows.length; i++) {
                                new_selectedRouteData.push({ id: changeRows[i].id, pushTime: changeRows[i].pushTime });
                                new_selectedRowKeys.push(changeRows[i].id);
                            }
                        } else {
                            for (let i = 0; i < changeRows.length; i++) {
                                const routeIndex = new_selectedRouteData.findIndex(item => item.id === changeRows[i].id), keyIndex = new_selectedRowKeys.indexOf(changeRows[i].id);
                                routeIndex > -1 && new_selectedRouteData.splice(routeIndex, 1)
                                keyIndex > -1 && new_selectedRowKeys.splice(keyIndex, 1);
                            }
                        }

                        setSelectedRouteData(new_selectedRouteData)
                        setSelectedRowKeys(new_selectedRowKeys)
                    }
                }}
                columns={columns}
            />}
            <ModalForm
                title={'手动补推'}
                visible={visible}
                modalProps={{
                    centered: true,
                    destroyOnClose: true,
                    onCancel: () => {
                        setVisible(false);
                    }
                }}
                width="400px"
                labelCol={{ span: 6 }}
                layout={'horizontal'}
                onFinish={async (values) => {
                    const { datetimeRange, ...others } = values;
                    const msg = await repushByDb({
                        startTime: datetimeRange[0],
                        endTime: datetimeRange[1],
                        ...others
                    });
                    if (msg.code === 0) {
                        message.success('操作成功');
                        actionRef.current?.reload();
                        setVisible(false);
                    }
                }}
            >
                <ProFormSelect width="md" name="expressId" label="快递公司" rules={[
                    {
                        required: true,
                    },
                ]} fieldProps={{
                    options: expressList,
                }} />
                <ProFormText label='运单号' width="md" name="expCodeList" fieldProps={{ maxLength: 32 }} rules={[
                    {
                        required: true,
                    },
                ]} />
                <ProFormSelect width="md" name="event" label="类型" rules={[
                    {
                        required: true,
                    },
                ]} fieldProps={{
                    options: [
                        { label: '入库', value: 'deliver' },
                        { label: '出库', value: 'pickup' },
                        { label: '退回', value: 'withdraw' },
                    ],
                }} />
                <ProFormDateTimeRangePicker name="datetimeRange" label="推送时间" rules={[
                    {
                        required: true,
                    },
                ]} />
            </ModalForm>
        </PageContainer >
    );
};

export default ExpressRouteList;
